<template>
  <view class="warehouse-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <text class="page-title">出库作业</text>
    </view>

    <!-- 出库信息区域 -->
    <view class="info-section">
      <view class="section-header">
        <text class="section-title">出库信息</text>
      </view>

      <!-- 出库类型标签页 -->
      <view class="in-type-tabs">
        <view
          class="tab-item"
          :class="{ active: formData.outType === 'batch' }"
          @click="switchOutType('领料出库')"
        >
          <text class="tab-text">领料出库</text>
        </view>
        <view
          class="tab-item"
          :class="{ active: formData.outType === 'manual' }"
          @click="switchOutType('人工出库')"
        >
          <text class="tab-text">人工出库</text>
        </view>
        <view
          class="tab-item"
          :class="{ active: formData.outType === 'transfer' }"
          @click="switchOutType('调拨出库')"
        >
          <text class="tab-text">调拨出库</text>
        </view>
      </view>

      <view class="info-form">
        <view class="form-item">
          <text class="form-label">出库日期</text>
          <picker
            mode="date"
            :value="formData.queryDate"
            @change="handleDateChange"
          >
            <view class="warehouse-picker">
              <text class="warehouse-display">{{ formData.queryDate }}</text>
              <text class="picker-arrow">▼</text>
            </view>
          </picker>
        </view>
        <view class="form-item">
          <text class="form-label">源仓库</text>
          <view class="warehouse-display">{{
            currentWarehouse ? currentWarehouse.warehouseName : "请选择"
          }}</view>
        </view>

        <!-- 领料部门 -->
        <view class="form-item">
          <text class="form-label">领料部门</text>
          <picker
            class="form-picker"
            mode="selector"
            :range="deptOptions"
            range-key="name"
            :value="deptIndex"
            @change="handleDeptChange"
          >
            <view class="picker-content">
              <text>{{
                deptIndex >= 0 && deptOptions[deptIndex]
                  ? deptOptions[deptIndex].name
                  : "请选择领料部门"
              }}</text>
              <text class="picker-arrow">></text>
            </view>
          </picker>
        </view>

        <!-- 领料工序 -->
        <view class="form-item">
          <text class="form-label">领料工序</text>
          <picker
            class="form-picker"
            mode="selector"
            :range="processOptions"
            range-key="text"
            :value="processIndex"
            @change="handleProcessChange"
          >
            <view class="picker-content">
              <text>{{
                processIndex >= 0 && processOptions[processIndex]
                  ? processOptions[processIndex].text
                  : "请选择领料工序"
              }}</text>
              <text class="picker-arrow">></text>
            </view>
          </picker>
        </view>

        <!-- 调拨目标仓库（仅调拨出库显示） -->
        <view class="form-item" v-if="currentOutType === '调拨出库'">
          <text class="form-label required">目标仓库</text>
          <picker
            class="form-picker"
            mode="selector"
            :range="targetWarehouseOptions"
            range-key="warehouseName"
            :value="targetWarehouseIndex"
            @change="handleTargetWarehouseChange"
          >
            <view class="picker-content">
              <text>{{
                targetWarehouseIndex >= 0 &&
                targetWarehouseOptions[targetWarehouseIndex]
                  ? targetWarehouseOptions[targetWarehouseIndex].warehouseName
                  : "请选择目标仓库"
              }}</text>
              <text class="picker-arrow">></text>
            </view>
          </picker>
        </view>
      </view>
    </view>

    <!-- 物料编码查询，使用统一的扫码组件 -->
    <view class="material-section">
      <view class="scan-section">
        <ScanInput
          v-model="searchForm.materialCode"
          placeholder="请输入物料编码或扫码"
          tip-text="物料扫码查询"
          :loading="isLoading"
          :on-scan-result="handleMaterialScanResult"
          :on-confirm="handleMaterialScanResult"
          ref="scanInputRef"
        />
      </view>
    </view>

    <!-- 领料单查询和库存查询 TAB 页面 -->
    <view class="query-tabs-section">
      <!-- TAB 导航 -->
      <view class="query-tabs">
        <view
          class="query-tab-item"
          :class="{ active: activeQueryTab === 'batch' }"
          @click="switchQueryTab('batch')"
        >
          <text class="query-tab-text">领料单查询</text>
        </view>
        <view
          class="query-tab-item"
          :class="{ active: activeQueryTab === 'stock' }"
          @click="switchQueryTab('stock')"
        >
          <text class="query-tab-text">库存查询</text>
        </view>
      </view>

      <!-- 领料单查询内容 -->
      <view
        class="query-tab-content"
        v-if="activeQueryTab === 'batch' && currentOutType === '领料出库'"
      >
        <view class="section-header">
          <text class="section-title">领料单查询</text>
          <!-- 第一行：时间筛选按钮组 -->
          <view class="time-filter-buttons">
            <button
              class="filter-btn"
              :class="{ active: batchTimeFilter === 'today' }"
              @click="handleBatchTimeChange('today')"
            >
              当日
            </button>
            <button
              class="filter-btn"
              :class="{ active: batchTimeFilter === 'yesterday' }"
              @click="handleBatchTimeChange('yesterday')"
            >
              昨日
            </button>
            <button
              class="filter-btn"
              :class="{ active: batchTimeFilter === 'week' }"
              @click="handleBatchTimeChange('week')"
            >
              近7天
            </button>
            <button
              class="filter-btn"
              :class="{ active: batchTimeFilter === 'month' }"
              @click="handleBatchTimeChange('month')"
            >
              近30天
            </button>
          </view>
        </view>
        <!-- 领料单匹配表格 -->
        <view
          class="batch-table-section"
          v-if="showBatchTable && batchTable.length > 0"
        >
          <scroll-view
            class="table-scroll"
            scroll-y
            scroll-x
            @scroll="handleBatchTableScroll"
            @scrolltolower="loadMoreBatches"
            ref="batchTableScroll"
          >
            <view class="table-row header">
              <text class="header-cell">钢种</text>
              <text class="header-cell">物料名称</text>
              <text class="header-cell">配料重量(KG)</text>
              <text class="header-cell">创建日期</text>
              <text class="header-cell">物料编码</text>
            </view>
            <view
              v-for="(item, index) in batchTable.slice(
                0,
                batchPageSize * batchCurrentPage
              )"
              :key="index"
              class="table-row"
              :class="{
                selected: selectedBatch && selectedBatch.id === item.id,
              }"
            >
              <text class="table-cell">{{ item.steelGrade || "-" }}</text>
              <text class="table-cell">{{ item.materialName || "-" }}</text>
              <text class="table-cell">{{ item.materialWeight || 0 }}</text>
              <text class="table-cell">{{
                dateHelperApi.formatDate(item.createTime)
              }}</text>
              <text class="table-cell">{{ item.materialCode || "-" }}</text>
            </view>
          </scroll-view>

          <!-- 横向滚动提示 -->
          <view
            class="scroll-hint"
            v-if="showBatchScrollHint"
            :class="{ 'scroll-hint-hidden': !showBatchScrollHint }"
          >
            <text class="scroll-hint-text">→ 横向滑动查看更多信息</text>
          </view>

          <!-- 加载更多 -->
          <view
            v-if="batchTable.length > batchPageSize * batchCurrentPage"
            class="load-more"
            @click="loadMoreBatches"
          >
            <text class="load-more-text">点击加载更多</text>
          </view>
        </view>
      </view>

      <!-- 库存查询内容 - 简化显示 -->
      <view class="query-tab-content" v-if="activeQueryTab === 'stock'">
        <!-- 库存数据直接显示，无需额外查询条件 -->
      </view>
    </view>

    <!-- 库存物料表格 - 直接显示库存数据 -->
    <view class="material-table-section">
      <scroll-view
        class="table-scroll"
        scroll-y
        scroll-x
        @scroll="handleStockTableScroll"
        ref="stockTableScroll"
      >
        <view class="table-row header">
          <text class="header-cell">选择</text>
          <text class="header-cell">物料名称</text>
          <text class="header-cell">库存重量(KG)</text>
          <text class="header-cell">库存数量(件)</text>
          <text class="header-cell">出库重量(KG)</text>
          <text class="header-cell">出库数量(件)</text>
          <text class="header-cell">物料编码</text>
          <text class="header-cell">操作</text>
        </view>
        <view
          v-for="(item, index) in stockTable"
          :key="item.id"
          class="table-row"
          :class="{
            selected: selectedStockRows.some((row) => row.id === item.id),
          }"
          @click="toggleStockSelection(item)"
        >
          <view class="table-cell">
            <view class="custom-checkbox" @click="toggleStockSelection(item)">
              <view
                class="checkbox-icon"
                :class="{
                  'checkbox-checked': selectedStockRows.some(
                    (row) => row.id === item.id
                  ),
                }"
              >
                <text
                  v-if="selectedStockRows.some((row) => row.id === item.id)"
                  class="check-mark"
                  >✓</text
                >
              </view>
            </view>
          </view>
          <text class="table-cell">{{ item.materialName || "-" }}</text>
          <text class="table-cell">{{ item.prodCount || 0 }}</text>
          <text class="table-cell">{{ item.transCount || 0 }}</text>
          <view class="table-cell quantity-cell">
            <input
              type="digit"
              v-model="item.outProdCount"
              @input="validateNumber($event, item, 'outProdCount')"
              class="quantity-input large-input"
              placeholder="请输入重量"
            />
          </view>
          <view class="table-cell quantity-cell">
            <input
              type="number"
              v-model="item.outTransCount"
              @input="validateNumber($event, item, 'outTransCount')"
              class="quantity-input large-input"
              placeholder="请输入数量"
            />
          </view>
          <text class="table-cell">{{ item.materialCode || "-" }}</text>
          <view class="table-cell">
            <button
              class="remove-btn-small"
              @click="deleteStockRow(index)"
              size="mini"
              type="warn"
            >
              删除
            </button>
          </view>
        </view>
      </scroll-view>

      <!-- 横向滚动提示 -->
      <view
        class="scroll-hint"
        v-if="showStockScrollHint"
        :class="{ 'scroll-hint-hidden': !showStockScrollHint }"
      >
        <text class="scroll-hint-text">→ 横向滑动查看更多信息</text>
      </view>
    </view>

    <!-- 统计信息 - 显示选中的库存物料统计 -->
    <view class="statistics-section">
      <view class="stat-item">
        <text class="stat-label">选中总数量</text>
        <text class="stat-value">{{ totalQuantity }}</text>
      </view>
      <view class="stat-item">
        <text class="stat-label">选中总重量</text>
        <text class="stat-value">{{ totalWeight }} KG</text>
      </view>
    </view>

    <!-- 库存查询提示 - 当没有数据时显示 -->
    <view
      class="empty-stock-tip"
      v-if="activeQueryTab === 'stock' && stockTable.length === 0"
    >
    </view>

    <!-- 底部操作栏 -->
    <view class="action-bar">
      <view class="button-row">
        <button class="btn-reset" @click="resetForm">重置</button>
        <button class="btn-submit" @click="submitForm">提交出库</button>
      </view>
    </view>
  </view>
</template>

<script>
import { dateHelperApi } from "@/pages/smart/warehouse/utils/date-helper";
// 导入物料API
import { MaterialApi } from "@/api/md/material/index.js";
// 导入库存API
import { inventoryApi } from "@/api/warehouse/inventory";
// 导入出库API
import { stockOutApi } from "@/api/warehouse/stockOut";
// 导入领料单API
import { SxBatchApi } from "@/api/pp/sxbatch/index.js";
// 导入仓库API
import { warehouseApi } from "@/api/warehouse/warehouse.js";
// 导入部门API
import { getDeptList } from "@/api/system/dept.js";
// 导入工序API
import { getProcessOptions } from "@/api/md/process.js";
// 导入PDA扫码
import ScanInput from "@/components/ScanInput/ScanInput.vue";
// 导入数采计量工具
import { getDasKey } from "@/pages/smart/utils/das.js";

export default {
  name: "OutWarehouseCreate",
  components: {
    ScanInput,
  },
  data() {
    return {
      // 出库类型配置
      outTypeOptions: [
        { value: "领料出库", label: "领料出库" },
        { value: "人工出库", label: "人工出库" },
        { value: "调拨出库", label: "调拨出库" },
      ],
      outTypeIndex: 0,

      // 表单数据
      formData: {
        outType: "batch",
        queryDate: dateHelperApi.getCurrentDate(), // 修改为queryDate，与报表页面保持一致
        sourceWarehouseId: "",
        sourceWarehouseName: "",
        targetWarehouseId: "", // 调拨出库专用
        targetWarehouseName: "", // 调拨出库专用
        reserveVarchar1: "", // 领料部门
        reserveVarchar2: "", // 领料工序
        isLoading: false,
      },

      // 时间筛选器
      timeFilter: "today",

      // 搜索表单
      searchForm: {
        materialName: "",
        supplierId: "",
        supplierName: "",
        quantity: null, // 新增：数量输入
        materialCode: "", // 新增：物料编码输入
      },

      // 数量单位相关
      unitIndex: 0, // 默认选中第一个单位
      unitOptions: ["件", "个", "套", "台"], // 单位选项

      // 物料编码输入
      materialCode: "", // 新增：物料编码输入
      materialName: "", // 新增：物料名称输入

      // 数据列表
      supplierList: [],
      supplierIndex: -1,
      documentList: [],
      materialList: [],
      currentWarehouse: null,

      // 库存物料表格数据
      stockTable: [], // 库存查询结果
      selectedStockRows: [], // 选中的库存行列表（支持多选）

      // 物料表格数据
      materialTable: [], // 物料查询结果
      selectedMaterialRows: [], // 选中的物料行列表（支持多选）

      // 领料单数据
      batchTable: [], // 领料单列表
      selectedBatch: null, // 选中的领料单（单选模式）
      batchTimeFilter: "today", // 领料单查询区域时间筛选
      batchCurrentPage: 1, // 领料单当前页
      batchPageSize: 10, // 领料单每页条数

      // 待出库物料表格
      outTable: [], // 待出库物料列表

      // Tab选项卡状态
      activeTab: "current", // 当前激活的tab: 'current' (当前数据) 或 'selected' (选中待出库)

      // 查询TAB状态
      activeQueryTab: "stock", // 当前激活的查询tab: 'batch' (领料单) 或 'stock' (库存)

      // 字段显示控制
      hiddenFields: ["id", "supplier", "vehicleno"], // 不显示的字段列表

      // 显示控制
      showDocumentList: false,
      showBatchTable: false, // 显示领料单表格

      // 调拨相关
      targetWarehouseOptions: [], // 目标仓库选项
      targetWarehouseIndex: -1, // 目标仓库选择索引

      // 领料相关
      deptOptions: [], // 部门选项
      deptIndex: -1, // 部门选择索引
      processOptions: [], // 工序选项
      processIndex: -1, // 工序选择索引

      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 5,
        startDate: "", // 开始日期
        endDate: "", // 结束日期
      },

      // 时间范围
      timeRange: {
        startTime: "",
        endTime: "",
      },

      // 加载状态
      isLoading: false,
      inputMethodEnabled: false,

      // 表格滚动提示控制
      showBatchScrollHint: false, // 领料单表格滚动提示
      showStockScrollHint: false, // 库存物料表格滚动提示

      // 统计数据
      totalWeight: 0, // 物料总重量
      totalQuantity: 0, // 物料总数量
      weightTotalWeight: 0, // 检斤总重量
      weightTotalQuantity: 0, // 检斤总数量
    };
  },

  computed: {
    // 暴露dateHelperApi供模板使用
    dateHelperApi() {
      return dateHelperApi;
    },

    currentOutType() {
      return this.outTypeOptions[this.outTypeIndex]?.value;
    },

    searchSectionTitle() {
      const titles = {
        batch: "领料单查询",
        manual: "库存查询",
        transfer: "库存查询",
      };
      return titles[this.currentOutType] || "查询";
    },

    totalOutWeight() {
      return this.outTable.reduce(
        (sum, item) => sum + (Number(item.outProdCount) || 0),
        0
      );
    },

    totalOutQuantity() {
      return this.outTable.reduce(
        (sum, item) => sum + (Number(item.outTransCount) || 0),
        0
      );
    },
  },

  mounted() {
    this.loadInitialData();
    this.loadDeptOptions(); // 加载部门选项
    this.loadProcessOptions(); // 加载工序选项

    // 初始化输入法状态
    this.initInputMethod();

    // 启动PDA扫码（如果设备支持）
    this.startPdaContinuousScan();
  },

  watch: {
    contractTable: {
      handler(newVal, oldVal) {
        console.log("contractTable发生变化:", {
          oldLength: oldVal ? oldVal.length : 0,
          newLength: newVal ? newVal.length : 0,
          newData: newVal,
        });
      },
      deep: true,
    },
    showContractTable: {
      handler(newVal, oldVal) {
        console.log("showContractTable发生变化:", {
          oldValue: oldVal,
          newValue: newVal,
        });
      },
    },
    currentOutType: {
      handler(newVal, oldVal) {
        console.log("出库类型发生变化:", {
          oldValue: oldVal,
          newValue: newVal,
        });
        // 当切换到调拨出库时，加载目标仓库数据
        if (newVal === "调拨出库") {
          this.loadTargetWarehouses();
        }
      },
    },
  },

  methods: {
    /**
     * 初始化输入法状态
     */
    initInputMethod() {
      // 从本地存储读取输入法状态
      const saved = uni.getStorageSync("inputMethodEnabled");
      if (saved !== null && saved !== undefined) {
        this.inputMethodEnabled = saved;
      }
    },

    /**
     * 切换出库类型
     */
    switchOutType(type) {
      const typeMap = {
        领料出库: "batch",
        人工出库: "manual",
        调拨出库: "transfer",
      };

      this.outTypeIndex = this.outTypeOptions.findIndex(
        (option) => option.label === type
      );
      this.formData.outType = typeMap[type];

      // 重置相关数据
      this.resetSearchData();

      // 根据类型加载初始数据
      if (type === "领料出库") {
        this.searchBatchData();
        this.activeQueryTab = "batch"; // 领料出库默认显示领料单查询
      } else if (type === "调拨出库") {
        this.loadTargetWarehouses();
        this.activeQueryTab = "stock"; // 调拨出库默认显示库存查询
      } else {
        this.activeQueryTab = "stock"; // 人工出库默认显示库存查询
      }
    },

    /**
     * 切换查询TAB
     */
    switchQueryTab(tab) {
      this.activeQueryTab = tab;
      // 切换到领料单查询时，如果当前是领料出库模式，重新加载领料单数据
      if (tab === "batch" && this.currentOutType === "领料出库") {
        this.searchBatchData();
      }
    },

    /**
     * 重置搜索数据
     */
    resetSearchData() {
      this.batchTable = [];
      this.selectedBatch = null;
      this.stockTable = [];
      this.selectedStockRows = [];
      this.outTable = [];
      this.showBatchTable = false;
      this.searchForm.materialName = "";
      this.searchForm.materialCode = "";
    },

    /**
     * 获取当前日期
     */
    getCurrentDate() {
      return dateHelperApi.formateTime(new Date());
    },

    /**
     * 处理日期选择
     */
    handleDateChange(e) {
      this.formData.queryDate = e.detail.value;
    },

    /**
     * 时间选择处理
     */
    handleTimeChange(timeFilter) {
      // 更新时间筛选器
      this.timeFilter = timeFilter;

      // 使用通用的updateDateRange函数
      const result = dateHelperApi.updateDateRange(timeFilter, {
        callback: ({ startDate, endDate }) => {
          // 更新时间范围
          this.timeRange = {
            startTime: startDate,
            endTime: endDate,
          };
        },
      });
    },

    /**
     * 处理目标仓库变更（调拨出库）
     */
    handleTargetWarehouseChange(e) {
      this.targetWarehouseIndex = parseInt(e.detail.value);
      if (this.targetWarehouseIndex >= 0) {
        this.formData.targetWarehouseId =
          this.targetWarehouseOptions[this.targetWarehouseIndex].warehouseCode;
        this.formData.targetWarehouseName =
          this.targetWarehouseOptions[this.targetWarehouseIndex].warehouseName;
      }
    },

    /**
     * 处理领料部门变更
     */
    handleDeptChange(e) {
      this.deptIndex = parseInt(e.detail.value);
      if (this.deptIndex >= 0) {
        this.formData.reserveVarchar1 = this.deptOptions[this.deptIndex].name;
      } else {
        this.formData.reserveVarchar1 = "";
      }
    },

    /**
     * 处理领料工序变更
     */
    handleProcessChange(e) {
      this.processIndex = parseInt(e.detail.value);
      if (this.processIndex >= 0) {
        this.formData.reserveVarchar2 =
          this.processOptions[this.processIndex].text;
      } else {
        this.formData.reserveVarchar2 = "";
      }
    },

    /**
     * 加载部门选项
     */
    async loadDeptOptions() {
      try {
        const response = await getDeptList();
        console.log("部门API响应:", response);

        if (response.code === 0 && response.data) {
          // 筛选parentId=200的部门，使用name字段
          this.deptOptions = response.data
            .filter((dept) => dept.parentId === 200)
            .map((dept) => ({
              ...dept,
              name: dept.name || dept.deptName || "未知部门",
            }));
          console.log("部门选项数量:", this.deptOptions.length);
          console.log("部门选项加载成功:", this.deptOptions);
        } else {
          console.error("加载部门失败:", response.msg);
          this.deptOptions = [];
        }
      } catch (error) {
        console.error("加载部门选项失败:", error);
        this.deptOptions = [];
      }
    },

    /**
     * 加载工序选项
     */
    async loadProcessOptions() {
      try {
        console.log("开始加载工序选项...");
        const options = await getProcessOptions();
        console.log("获取到的工序选项:", options);
        this.processOptions = options || [];
        console.log("工序选项加载成功:", this.processOptions);
      } catch (error) {
        console.error("加载工序选项失败:", error);
        this.processOptions = [];
      }
    },

    /**
     * 查询领料单
     */
    async searchBatchData() {
      if (this.isLoading) return;

      try {
        this.isLoading = true;
        this.batchTable = [];

        const params = {
          pageNo: 1,
          pageSize: 10,
          // batchNo: "PLJH2025102401", //测试数据
        };

        // 添加日期范围参数
        if (this.timeRange.startTime && this.timeRange.endTime) {
          // 添加时间范围参数
          if (this.timeRange.startTime && this.timeRange.endTime) {
            params.createTime = [
              this.timeRange.startTime,
              this.timeRange.endTime,
            ];
          }
        }

        const response = await SxBatchApi.getSxBatchDetailPage(params);

        if (response.code === 0) {
          this.batchTable = (response.data.list || []).map((item) => ({
            ...item,
            id: item.id || item.batchNo, // 确保有唯一ID
          }));
          this.showBatchTable = true;

          if (this.batchTable.length === 0) {
            uni.showToast({
              title: "未查询到领料单数据",
              icon: "none",
            });
          }
        } else {
          uni.showToast({
            title: response.msg || "查询失败",
            icon: "error",
          });
        }
      } catch (error) {
        console.error("查询领料单失败:", error);
        uni.showToast({
          title: "查询失败",
          icon: "error",
        });
      } finally {
        this.isLoading = false;
      }
    },

    /**
     * 选择领料单
     */
    selectBatch(batch) {
      // 仅设置选中的领料单信息，不执行查询操作
      this.selectedBatch = batch;
      this.searchForm.materialCode = batch.materialCode;
      this.searchForm.materialName = batch.materialName;
      // 不再自动查询库存，需要用户手动切换到库存查询TAB
    },

    /**
     * 切换库存选择状态
     */
    toggleStockSelection(stockItem) {
      const index = this.selectedStockRows.findIndex(
        (row) => row.id === stockItem.id
      );
      if (index >= 0) {
        this.selectedStockRows.splice(index, 1);
      } else {
        this.selectedStockRows.push(stockItem);
      }
      console.log("当前选中的库存行:", this.selectedStockRows);
    },

    /**
     * 获取时间筛选日期
     */
    getTimeFilterDate(filterType) {
      const now = new Date();
      let startDate = new Date();

      switch (filterType) {
        case "today":
          startDate = new Date(
            now.getFullYear(),
            now.getMonth(),
            now.getDate()
          );
          break;
        case "week":
          startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
          break;
        case "month":
          startDate = new Date(now.getFullYear(), now.getMonth(), 1);
          break;
        default:
          startDate = new Date(
            now.getFullYear(),
            now.getMonth(),
            now.getDate()
          );
      }

      return dateHelperApi.formatDate(startDate);
    },

    /**
     * 处理领料单时间筛选变化
     */
    handleBatchTimeChange(filterType) {
      this.batchTimeFilter = filterType;

      // 使用通用的updateDateRange函数
      const result = dateHelperApi.updateDateRange(filterType, {
        callback: ({ startDate, endDate }) => {
          // 更新时间范围
          this.timeRange = {
            startTime: startDate,
            endTime: endDate,
          };
          console.log("领料单查询时间范围:", {
            startDate,
            endDate,
          });
          // 确保时间范围设置完成后再执行查询
          this.$nextTick(() => {
            this.searchBatchData();
          });
        },
      });
    },

    /**
     * 数字输入校验
     */
    validateNumber(event, item, field) {
      const value = event.detail.value;

      // 处理空值情况
      if (value === "" || value === null || value === undefined) {
        item[field] = "";
        return;
      }

      const numValue = Number(value);

      // 确保为有效数字
      if (!this.isValidNumber(numValue)) {
        item[field] = "";
        return;
      }

      // 确保不为负数
      if (numValue < 0) {
        item[field] = "";
        return;
      }

      item[field] = numValue;
    },

    /**
     * 数字有效性验证
     */
    isValidNumber(value) {
      return !isNaN(value) && isFinite(value) && value >= 0;
    },

    /**
     * 加载更多领料单
     */
    loadMoreBatches() {
      // 当前实现为前端分页，可以扩展为后端分页
      if (this.batchTable.length > this.batchCurrentPage * this.batchPageSize) {
        this.batchCurrentPage++;
      }
    },

    /**
     * 加载初始数据
     */
    async loadInitialData() {
      // 加载当前仓库
      await this.getCurrentWarehouse();

      // 初始化时间范围并加载数据（按照报表页面模式）
      this.handleTimeChange("today");

      this.$nextTick(() => {
        // 根据当前出库类型加载数据
        if (this.currentOutType === "人工出库") {
          this.searchBatchData();
        } else if (this.currentOutType === "调拨出库") {
          this.loadTargetWarehouses();
        }
      });
    },

    /**
     * 初始化时间范围
     */
    initTimeRange() {
      // 使用updateDateRange初始化时间范围
      dateHelperApi.updateDateRange(this.batchTimeFilter, {
        callback: ({ startDate, endDate }) => {
          this.timeRange = {
            startTime: startDate,
            endTime: endDate,
          };
          console.log("初始化时间范围:", {
            startTime: startDate,
            endTime: endDate,
          });
        },
      });
    },

    /**
     * 获取当前仓库
     */
    async getCurrentWarehouse() {
      try {
        const response = await warehouseApi.getCurrentWarehouse();
        if (response.code === 0 && response.data) {
          this.currentWarehouse = response.data;
          this.formData.sourceWarehouseId = response.data.warehouseCode;
          this.formData.sourceWarehouseName = response.data.warehouseName;
        }
      } catch (error) {
        console.error("获取当前仓库失败:", error);
      }
    },

    /**
     * 加载目标仓库列表（调拨出库专用）
     */
    async loadTargetWarehouses() {
      try {
        const params = {
          pageNo: 1,
          pageSize: 100, // 获取较多数据
          dictType: "wm_name_po",
        };

        const response = await warehouseApi.getWarehouseList(params);
        console.log("目标仓库API响应:", response);
        if (response.code === 0) {
          // 将数据转换为下拉选项格式，根据API返回的字段名称
          this.targetWarehouseOptions = (response.data.list || []).map(
            (item) => ({
              value: item.value || item.warehouseCode,
              text: item.label || item.warehouseName,
              warehouseName: item.label || item.warehouseName, // 用于显示
            })
          );
          console.log("目标仓库数据加载成功:", this.targetWarehouseOptions);
          console.log("目标仓库选项数量:", this.targetWarehouseOptions.length);

          // 如果当前有仓库，设置对应的索引
          if (this.currentWarehouse && this.currentWarehouse.warehouseName) {
            const index = this.targetWarehouseOptions.findIndex(
              (option) =>
                option.warehouseName === this.currentWarehouse.warehouseName
            );
            if (index !== -1) {
              this.currentWarehouseIndex = index;
            }
          }
        }
      } catch (error) {
        console.error("加载目标仓库失败:", error);
        this.targetWarehouseOptions = [];
      }
    },

    /**
     * 重置表单
     */
    resetForm() {
      // 清空库存相关数据11
      this.stockTable = [];
      this.selectedStockRows = [];
      this.outTable = [];

      // 清空领料单相关数据
      this.batchTable = [];
      this.selectedBatch = null;
      this.showBatchTable = false;
      this.batchTimeFilter = "today";
      this.batchCurrentPage = 1;

      // 清空物料相关数据
      this.materialList = [];
      this.materialTable = [];
      this.selectedMaterialRows = [];

      // 清空供应商和单据数据
      this.supplierList = [];
      this.supplierIndex = -1;
      this.documentList = [];

      // 重置搜索表单
      this.searchForm.materialName = "";
      this.searchForm.materialCode = "";
      this.searchForm.supplierId = "";
      this.searchForm.supplierName = "";
      this.searchForm.quantity = null;

      // 重置物料编码输入
      this.materialCode = "";
      this.materialName = "";

      // 重置单位选择
      this.unitIndex = 0;

      // 重置查询参数
      this.queryParams.pageNo = 1;
      this.timeRange.startTime = "";
      this.timeRange.endTime = "";

      // 重置调拨相关
      this.targetWarehouseIndex = -1;

      // 重置显示控制
      this.activeTab = "current";
      this.showDocumentList = false;

      // 重置统计数据
      this.totalWeight = 0;
      this.totalQuantity = 0;
      this.weightTotalWeight = 0;
      this.weightTotalQuantity = 0;

      // 重置表单数据
      this.formData.queryDate = dateHelperApi.getCurrentDate();
      this.formData.targetWarehouseId = "";
      this.formData.targetWarehouseName = "";

      // 重新加载数据
      this.loadInitialData();
    },

    /**
     * 提交出库单
     */
    async submitForm() {
      if (this.isLoading) return;

      if (!this.validateForm()) {
        return;
      }
      console.log("提交出库单数据:", this.buildNewSubmitData());
      const confirmResult = await this.showSubmitConfirm(
        this.buildNewSubmitData()
      );
      if (!confirmResult) {
        return;
      }
      try {
        const submitData = this.buildNewSubmitData();
        let response;
        response = await stockOutApi.submitOutbound(submitData);

        if (response.code === 0) {
          await this.handleSubmitSuccess(response);
        } else {
          uni.showToast({
            title: response.msg || "提交失败",
            icon: "error",
          });
        }
      } catch (error) {
        console.error("提交出库单失败:", error);

        // 显示后端返回的具体错误信息
        let errorMsg = "提交失败";
        if (error.response && error.response.data) {
          const responseData = error.response.data;
          // 优先使用外层msg，如果没有则使用内层data.msg
          errorMsg =
            responseData.msg ||
            (responseData.data && responseData.data.msg) ||
            "提交失败";
        } else if (error.msg) {
          errorMsg = error.msg;
        }

        uni.showToast({
          title: errorMsg,
          icon: "error",
        });
      } finally {
        this.isLoading = false;
      }
    },

    /**
     * 表单验证
     */
    validateForm() {
      if (!this.currentWarehouse) {
        uni.showToast({
          title: "请选择源仓库",
          icon: "none",
        });
        return false;
      }

      if (!this.formData.queryDate) {
        uni.showToast({
          title: "请选择出库日期",
          icon: "none",
        });
        return false;
      }

      if (
        this.currentOutType === "调拨出库" &&
        !this.formData.targetWarehouseId
      ) {
        uni.showToast({
          title: "请选择目标仓库",
          icon: "none",
        });
        return false;
      }

      // 人工出库模式：验证stockTable中是否有填写了出库数量的物料
      const hasOutMaterials = this.stockTable.some(
        (item) =>
          (Number(item.outProdCount) || 0) > 0 ||
          (Number(item.outTransCount) || 0) > 0
      );
      if (!hasOutMaterials) {
        uni.showToast({
          title: "请填写出库物料数量",
          icon: "none",
        });
        return false;
      }

      // 验证出库数量

      // 人工出库模式：验证stockTable中填写了出库数量的物料
      for (let item of this.stockTable) {
        const outProdCount = Number(item.outProdCount) || 0;
        const outTransCount = Number(item.outTransCount) || 0;

        if (outProdCount > 0 || outTransCount > 0) {
          if (!this.isValidNumber(item.outProdCount) || outProdCount < 0) {
            uni.showToast({
              title: "出库重量必须大于0",
              icon: "none",
            });
            return false;
          }

          if (!this.isValidNumber(item.outTransCount) || outTransCount < 0) {
            uni.showToast({
              title: "出库数量必须大于0",
              icon: "none",
            });
            return false;
          }
        }
      }

      return true;
    },

    /**
     * 处理提交成功
     */
    async handleSubmitSuccess(response) {
      uni.showToast({
        title: "出库单创建成功",
        icon: "success",
        duration: 1000,
      });

      // 重置表单
      this.resetForm();
    },

    /**
     * 处理提交异常
     */
    async handleSubmitException(error) {
      console.error("提交表单异常:", error);

      let errorMsg = "提交失败，请重试";

      if (error.message && error.message.includes("Network")) {
        errorMsg = "网络连接失败，请检查网络后重试";
      } else if (error.code === "ECONNABORTED") {
        errorMsg = "请求超时，请稍后重试";
      } else if (error.response && error.response.status) {
        switch (error.response.status) {
          case 400:
            errorMsg = "请求参数错误，请检查输入数据";
            break;
          case 401:
            errorMsg = "登录已过期，请重新登录";
            break;
          case 403:
            errorMsg = "没有权限执行此操作";
            break;
          case 500:
            errorMsg = "服务器错误，请稍后重试";
            break;
          default:
            errorMsg = `服务器错误 (${error.response.status})，请稍后重试`;
        }
      }

      uni.showModal({
        title: "提交失败",
        content: errorMsg,
        showCancel: false,
        confirmText: "知道了",
      });
    },

    /**
     * 处理领料单表格滚动事件
     */
    handleBatchTableScroll(event) {
      const { scrollLeft, scrollWidth, clientWidth } = event.detail;
      // 当可以横向滚动且未滚动到最右侧时显示提示
      this.showBatchScrollHint =
        scrollWidth > clientWidth &&
        scrollLeft < scrollWidth - clientWidth - 10;
    },

    /**
     * 处理库存物料表格滚动事件
     */
    handleStockTableScroll(event) {
      const { scrollLeft, scrollWidth, clientWidth } = event.detail;
      // 当可以横向滚动且未滚动到最右侧时显示提示
      this.showStockScrollHint =
        scrollWidth > clientWidth &&
        scrollLeft < scrollWidth - clientWidth - 10;
    },

    async searchStockMaterials() {
      console.log("查询库存参数searchStockMaterials:", this.searchForm);
      try {
        this.isLoading = true;

        const params = {
          pageNum: 1,
          pageSize: 50,
          warehouseName: this.formData.sourceWarehouseName,
          materialCode: this.searchForm.materialCode, // 按物料编码查询
        };

        // 如果物料编码为空，不执行查询
        if (!this.searchForm.materialCode) {
          this.isLoading = false;
          return;
        }

        const response = await inventoryApi.queryInventory(params);

        if (response.code === 0) {
          // 人工出库模式下：直接将查询结果赋值到stockTable，用户直接在stockTable上填写出库数据
          this.stockTable = (response.data.list || []).map((item) => ({
            ...item,
            outProdCount: "",
            outTransCount: "",
          }));
          // 清空之前的选择状态和统计信息
          this.selectedStockRows = [];
          this.updateMaterialStatistics();
        } else {
          uni.showToast({
            title: "未查询到库存数据",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("查询库存失败:", error);
      } finally {
        this.isLoading = false;
      }
    },

    /**
     * 添加到出库列表
     */
    addToOutList(item) {
      // 检查是否已经添加
      const exists = this.outTable.find((outItem) => outItem.id === item.id);
      if (exists) {
        uni.showToast({
          title: "该物料已在出库列表中",
          icon: "none",
        });
        return;
      }

      // 验证出库数量
      const outProdCount = Number(item.outProdCount) || 0;
      const outTransCount = Number(item.outTransCount) || 0;

      if (outProdCount === 0 && outTransCount === 0) {
        uni.showToast({
          title: "出库重量和数量不能同时为0",
          icon: "none",
        });
        return;
      }

      if (outProdCount < 0 || outTransCount < 0) {
        uni.showToast({
          title: "出库数量不能为负数",
          icon: "none",
        });
        return;
      }

      // 检查库存是否足够
      if (outProdCount > (item.prodCount || 0)) {
        uni.showToast({
          title: "出库重量超过库存",
          icon: "none",
        });
        return;
      }

      if (outTransCount > (item.transCount || 0)) {
        uni.showToast({
          title: "出库数量超过库存",
          icon: "none",
        });
        return;
      }

      // 添加到出库列表
      this.outTable.push({
        ...item,
        outProdCount: outProdCount,
        outTransCount: outTransCount,
      });

      uni.showToast({
        title: "已添加到出库列表",
        icon: "success",
      });
    },

    /**
     * 从出库列表移除
     */
    removeFromOutList(index) {
      this.outTable.splice(index, 1);
    },

    /**
     * 切换库存选择状态
     */
    toggleStockSelection(item) {
      const index = this.selectedStockRows.findIndex(
        (row) => row.id === item.id
      );
      if (index > -1) {
        this.selectedStockRows.splice(index, 1);
      } else {
        this.selectedStockRows.push(item);
      }
      // 更新统计信息
      this.updateMaterialStatistics();
    },

    /**
     * 获取时间筛选日期
     */
    getTimeFilterDate(filterType) {
      const today = new Date();
      let startDate = new Date();

      switch (filterType) {
        case "today":
          startDate = today;
          break;
        case "week":
          startDate.setDate(today.getDate() - 7);
          break;
        case "month":
          startDate.setDate(today.getDate() - 30);
          break;
        default:
          startDate = today;
      }

      return dateHelperApi.formatDate(startDate);
    },

    /**
     * 处理领料单时间筛选变化
     */
    handleBatchTimeChange(filterType) {
      this.batchTimeFilter = filterType;

      // 使用通用的updateDateRange函数
      const result = dateHelperApi.updateDateRange(filterType, {
        callback: ({ startDate, endDate }) => {
          // 更新时间范围
          this.timeRange = {
            startTime: startDate,
            endTime: endDate,
          };
          console.log("领料单查询时间范围:", {
            startDate,
            endDate,
          });
          // 确保时间范围设置完成后再执行查询
          this.$nextTick(() => {
            this.searchBatchData();
          });
        },
      });
    },

    /**
     * 数字输入校验
     */
    validateNumber(event, item, field) {
      const value = event.target.value;

      // 处理空值情况
      if (value === "" || value === null || value === undefined) {
        item[field] = "";
        // 同步到统一计算的字段
        if (field === "prodCount") {
          item.weight = 0;
        } else if (field === "transCount") {
          item.quantity = 0;
        }
        this.updateMaterialStatistics();
        return;
      }

      // 只允许数字和小数点
      const validValue = value.replace(/[^0-9.]/g, "");

      // 处理多个小数点的情况
      const parts = validValue.split(".");
      if (parts.length > 2) {
        item[field] = parts[0] + "." + parts.slice(1).join("");
      } else {
        item[field] = validValue;
      }

      // 同步到统一计算的字段
      if (field === "prodCount") {
        item.weight = Number(item.prodCount || 0);
      } else if (field === "transCount") {
        item.quantity = Number(item.transCount || 0);
      }

      // 如果输入了有效的出库数量，自动选中该行
      const outProdCount = Number(item.outProdCount || 0);
      const outTransCount = Number(item.outTransCount || 0);

      if (outProdCount > 0 || outTransCount > 0) {
        // 检查是否已选中，如果没有则自动选中
        const isSelected = this.selectedStockRows.some(
          (row) => row.id === item.id
        );
        if (!isSelected) {
          this.selectedStockRows.push(item);
        }
      } else {
        // 如果数量都变为0，取消选中
        const selectedIndex = this.selectedStockRows.findIndex(
          (row) => row.id === item.id
        );
        if (selectedIndex > -1) {
          this.selectedStockRows.splice(selectedIndex, 1);
        }
      }

      // 更新统计信息
      this.updateMaterialStatistics();
    },

    /**
     * 删除库存表行
     */
    deleteStockRow(index) {
      uni.showModal({
        title: "确认删除",
        content: "确定要删除这条库存记录吗？",
        success: (res) => {
          if (res.confirm) {
            const deletedItem = this.stockTable[index];
            // 从选中列表中移除
            const selectedIndex = this.selectedStockRows.findIndex(
              (row) => row.id === deletedItem.id
            );
            if (selectedIndex > -1) {
              this.selectedStockRows.splice(selectedIndex, 1);
              // 更新统计信息
              this.updateMaterialStatistics();
            }
            this.stockTable.splice(index, 1);
            uni.showToast({
              title: "删除成功",
              icon: "success",
              duration: 1500,
            });
          }
        },
      });
    },

    /**
     * 切换物料行选择状态
     */
    toggleMaterialSelection(item) {
      const index = this.selectedMaterialRows.findIndex(
        (row) => row.id === item.id
      );
      if (index > -1) {
        this.selectedMaterialRows.splice(index, 1);
      } else {
        this.selectedMaterialRows.push(item);
      }
      // 更新统计信息
      this.updateMaterialStatistics();
    },

    /**
     * 切换检斤行选择状态
     */
    toggleWeightSelection(item) {
      const index = this.selectedWeightRows.findIndex(
        (row) => row.id === item.id
      );
      if (index > -1) {
        this.selectedWeightRows.splice(index, 1);
      } else {
        this.selectedWeightRows.push(item);
      }
      this.updateWeightStatistics();
    },

    /**
     * 更新物料统计信息
     */
    updateMaterialStatistics() {
      // 计算选中的库存行的统计信息（用于出库单）
      if (!this.selectedStockRows || !Array.isArray(this.selectedStockRows)) {
        this.totalWeight = 0;
        this.totalQuantity = 0;
        return;
      }

      this.totalWeight = this.selectedStockRows.reduce(
        (sum, item) => sum + Number(item.outProdCount || 0),
        0
      );
      this.totalQuantity = this.selectedStockRows.reduce(
        (sum, item) => sum + Number(item.outTransCount || 0),
        0
      );
    },

    /**
     * 启动PDA连续扫码
     * 在输入法关闭时启用PDA扫码，开启时使用输入法
     */
    startPdaContinuousScan() {
      // 只有在输入法关闭时才启用PDA扫码
      if (!this.inputMethodEnabled) {
        const success = this.startPdaScan((barcode) => {
          // 扫码结果处理
          this.handleMaterialScanResult(barcode);
        });

        if (success) {
          console.log("PDA连续扫码已启动");
        } else {
          console.warn("PDA扫码启动失败，将使用手动输入模式");
        }
      }
    },

    /**
     * 处理物料扫码结果
     * @param {string} barcode - 扫码得到的条码内容
     */
    async handleMaterialScanResult(barcode) {
      if (!barcode) return;
      this.isLoading = true;
      console.log("PDA物料扫码结果:", barcode);

      // 如果扫码内容以DAS开头，则调用数采计量方法
      if (barcode.startsWith("DAS")) {
        await this.handleMeasureWeight(barcode);
        this.isLoading = false;
        return;
      }

      this.materialTable = [];
      // 将扫码结果赋值给搜索框
      this.searchForm.materialCode = barcode;
      console.log("handleMaterialScanResult:", this.currentOutType);

      // 如果在库存查询tab页，直接查询库存
      if (this.activeQueryTab === "stock") {
        try {
          await this.searchStockMaterials();
        } catch (error) {
          console.error("查询库存失败:", error);
          uni.showToast({
            title: "查询库存失败，请重试",
            icon: "none",
            duration: 2000,
          });
        } finally {
          this.isLoading = false;
        }
        return;
      }

      // 人工出库或调拨出库模式下，扫码获取物料编码后查询主数据
      if (
        this.currentOutType === "人工出库" ||
        this.currentOutType === "调拨出库"
      ) {
        try {
          console.log("当前出库类型1:", this.currentOutType);
          await this.searchStockMaterials();
        } catch (error) {
          console.error("查询物料主数据失败:", error);
          uni.showToast({
            title: "查询失败，请重试",
            icon: "none",
            duration: 2000,
          });
        } finally {
          this.isLoading = false;
        }
      } else {
        // 其他模式下不执行合同匹配
        this.isLoading = false;
      }
    },

    /**
     * 数采计量方法
     * 当扫码内容以DAS开头时调用，获取计量数据并赋值到库存列表
     */
    async handleMeasureWeight(parameterName) {
      try {
        // 显示加载提示
        uni.showLoading({
          title: "计量中...",
        });

        // 调用getDasKey方法获取计量数据
        const result = await getDasKey(parameterName);
        console.log("数采result.result[0].v:", result.result[0].v);
        uni.hideLoading();

        // 处理返回的数据
        let weightValue = null;
        if (result) {
          weightValue = result.result[0].v || 0;
        }

        if (weightValue !== null && weightValue !== undefined) {
          const parsedValue = parseFloat(weightValue);
          if (!isNaN(parsedValue)) {
            // 判断库存列表是否有数据
            if (this.stockTable && this.stockTable.length > 0) {
              // 将计量值赋值到第一行的出库重量(KG)列
              this.stockTable[0].outProdCount = parsedValue;
              uni.showToast({
                title: `计量成功：${parsedValue}KG`,
                icon: "success",
              });
            } else {
              uni.showToast({
                title: "当前没有可赋值的库存数据",
                icon: "none",
              });
            }
          } else {
            uni.showToast({
              title: "获取到的计量数据格式不正确",
              icon: "none",
            });
          }
        } else {
          uni.showToast({
            title: "未找到对应的数采配置或数据为空",
            icon: "none",
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error("计量失败:", error);
        uni.showToast({
          title: error.message || "计量失败，请检查数采配置",
          icon: "none",
        });
      }
    },

    // 聚焦到输入框（输入法开启时弹出键盘）
    focusMaterialInput() {
      if (this.inputMethodEnabled && this.$refs.materialInput) {
        this.$nextTick(() => {
          if (this.$refs.materialInput.focus) {
            this.$refs.materialInput.focus();
          }
        });
      }
    },

    /**
     * 输入法开关切换处理
     */
    handleInputMethodSwitchChange() {
      this.inputMethodEnabled = !this.inputMethodEnabled;

      // 保存到本地存储
      uni.setStorageSync("inputMethodEnabled", this.inputMethodEnabled);

      // 如果开启输入法，聚焦输入框
      if (this.inputMethodEnabled) {
        this.focusMaterialInput();
        // 停止PDA扫码
        this.stopPdaScan();
      } else {
        // 如果关闭输入法，启动PDA扫码
        this.startPdaContinuousScan();
      }
    },

    // 时间筛选器变更处理（兼容旧版本）
    handleTimeChange(filter) {
      this.timeFilter = filter;
      dateHelperApi.updateDateRange(filter, {
        callback: ({ startDate, endDate }) => {
          this.queryParams.startDate = startDate;
          this.queryParams.endDate = endDate;
          console.log("时间筛选（兼容模式）:", {
            startDate,
            endDate,
          });
          // 根据当前入库类型执行相应的查询
          if (this.currentInType === "weigh" && this.searchForm.materialName) {
            this.searchWeighData();
          } else if (
            this.currentInType === "purchase" &&
            this.searchForm.materialName
          ) {
            // this.matchContract(); // 已删除此方法
          }
        },
      });
    },

    // 加载初始数据
    async loadInitialData() {
      try {
        // 初始化日期范围（根据默认选中的时间筛选器）
        dateHelperApi.updateDateRange(this.timeFilter, {
          callback: ({ startDate, endDate }) => {
            this.queryParams.startDate = startDate;
            this.queryParams.endDate = endDate;
          },
        });

        const warehouseRes = await this.getCurrentWarehouse();
        if (warehouseRes) {
          this.currentWarehouse = warehouseRes;
          this.formData.warehouseId = warehouseRes.warehouseId;
          this.formData.warehouseName = warehouseRes.warehouseName;
        }

        // 页面加载时不再默认查询合同信息
        // this.$nextTick(() => {
        //   setTimeout(() => {
        //     this.matchContract();
        //   }, 500);
        // });
      } catch (error) {
        console.error("加载初始数据失败:", error);
      }
    },

    // 获取当前用户仓库
    async getCurrentWarehouse() {
      try {
        // 从Vuex store获取用户配置的仓库信息
        const userConfig = this.$store.state.user.userConfig;
        if (userConfig && userConfig.wmName) {
          return {
            warehouseId: userConfig.warehouseId || "DEFAULT",
            warehouseName: userConfig.wmName,
          };
        }

        // 降级处理：尝试其他字段
        if (userConfig && userConfig.warehouseName) {
          return {
            warehouseId: userConfig.warehouseId || "DEFAULT",
            warehouseName: userConfig.warehouseName,
          };
        }
      } catch (error) {
        console.error("获取用户仓库失败:", error);
      }
    },

    // 清除原表格中的选中状态
    clearOriginalTableSelection() {
      this.materialTable.forEach((item) => {
        if (item.isCheck) {
          this.$set(item, "isCheck", false);
          this.$set(item, "showError", false);
          this.$set(item, "prod_count", 0);
          this.$set(item, "trans_count", 0);
        }
      });
    },

    // 处理返回按钮点击
    handleBack() {
      // 检查是否有未入库的数据
      if (this.materialList.length > 0) {
        uni.showModal({
          title: "提示",
          content: "有数据未出库，请先提交出库或删除待出库数据",
          confirmText: "去提交",
          cancelText: "删除数据",
          success: (res) => {
            if (res.confirm) {
              // 用户选择去提交，不做任何操作
              return;
            } else if (res.cancel) {
              // 用户选择删除数据，清空materialList
              this.stockTable = [];
              // 同时清除原表格中的选中状态
              this.clearOriginalTableSelection();
              // 返回上一页
              uni.navigateBack();
            }
          },
        });
      } else {
        // 没有数据，直接返回
        uni.navigateBack();
      }
    },

    // 重置所有查询结果表
    resetQueryResults() {
      // 重置合同表
      this.contractTable = [];
      this.showContractTable = false;

      // 重置检斤表
      this.weightTable = [];
      this.showWeightTable = false;
      this.selectedWeightRow = null;

      // 重置物料表
      this.materialTable = [];

      // 重置物料编码和名称输入
      this.materialCode = "";
      this.materialName = "";

      // 重置时间筛选 - 保持各自区域的独立性
      this.contractTimeFilter = "today";
      this.weighTimeFilter = "today";
      this.timeFilter = "today";
    },

    // 日期变更
    handleDateChange(e) {
      // 获取选择的日期
      const selectedDate = e.detail.value;
      // 使用dateHelperApi格式化日期时间
      this.formData.inDate = dateHelperApi.formatDateTime(selectedDate);
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        materialName: "",
        supplierId: "",
        supplierName: "",
        quantity: null, // 重置数量
        materialCode: "", // 重置物料编码
      };
      this.unitIndex = 0; // 重置单位选择
      this.supplierIndex = -1;
      this.documentList = [];
      this.showDocumentList = false;
      this.selectedWeightRows = []; // 清空多选列表

      // 重置各自区域的时间筛选
      this.contractTimeFilter = "today";
      this.weighTimeFilter = "today";
    },

    // 验证搜索数量输入
    validateSearchQuantity() {
      if (
        this.searchForm.quantity !== null &&
        this.searchForm.quantity !== undefined
      ) {
        // 确保数量为有效数字且大于0
        const quantity = Number(this.searchForm.quantity);
        if (isNaN(quantity) || quantity <= 0) {
          uni.showToast({
            title: "请输入有效的数量（大于0）",
            icon: "none",
          });
          this.searchForm.quantity = null;
        } else if (quantity > 999999) {
          uni.showToast({
            title: "数量超出范围（最大999999）",
            icon: "none",
          });
          this.searchForm.quantity = 999999;
        }
      }
    },

    // 处理单位选择变化
    handleUnitChange(e) {
      this.unitIndex = e.detail.value;
    },

    // 获取单位索引
    getUnitIndex(unit) {
      return this.unitOptions.indexOf(unit) !== -1
        ? this.unitOptions.indexOf(unit)
        : 0;
    },

    // 验证检斤行数量输入
    validateWeightQuantity(event, item) {
      const value = Number(event.target.value);
      if (isNaN(value) || value < 0) {
        uni.showToast({
          title: "请输入有效的数量（不小于0）",
          icon: "none",
        });
        item.quantity = 0;
      } else if (value > 999999) {
        uni.showToast({
          title: "数量超出范围（最大999999）",
          icon: "none",
        });
        item.quantity = 999999;
      }
    },

    // 更新检斤统计信息
    updateWeightStatistics() {
      // 计算选中检斤行的总净重和总数量
      const totalWeight = this.selectedWeightRows.reduce(
        (sum, item) => sum + (Number(item.actualwt) || 0),
        0
      );
      const totalQuantity = this.selectedWeightRows.reduce(
        (sum, item) => sum + (Number(item.quantity) || 0),
        0
      );

      // 更新统计信息（转换为显示单位）
      this.weightTotalWeight = totalWeight;
      this.weightTotalQuantity = totalQuantity;

      console.log("检斤统计信息更新:", {
        selectedRows: this.selectedWeightRows.length,
        totalWeight: totalWeight,
        totalQuantity: totalQuantity,
      });
    },

    // 搜索物料（保留原有方法用于其他入库类型）
    async searchMaterials() {
      try {
        let res;
        if (this.currentInType === "weigh") {
          // 检斤入库现在使用专门的searchWeighData方法
          return;
        } else {
          res = await queryMaterial({
            materialCode: this.materialCode,
            materialName: this.materialName,
            pageNum: 1,
            pageSize: 20,
          });
        }
        if (res.code === 0) {
          // 根据入库类型决定数据存储位置
          if (
            this.currentInType === "purchase" ||
            this.currentInType === "manual"
          ) {
            // 采购入库：直接显示在物料表格中，确保重量和数量默认为0
            // 保留已确认的物料状态，新搜索的物料展现在未确认物料中
            const newMaterials = (res.data?.list || []).map((item) => {
              // 检查该物料是否已经在materialTable中存在且已确认
              const existingItem = this.materialTable.find(
                (tableItem) =>
                  tableItem.materialCode === item.materialCode &&
                  tableItem.isCheck
              );

              if (existingItem) {
                // 如果已存在且已确认，保持其状态
                return existingItem;
              } else {
                // 新物料或未确认的物料
                return {
                  ...item,
                  prod_count: 0, // 重量默认为0
                  trans_count: 0, // 数量默认为0
                  isCheck: false, // 确认状态默认为false
                  showError: false, // 错误状态默认为false
                };
              }
            });

            this.materialTable = newMaterials;
          }
        }
      } catch (error) {
        console.error("搜索物料失败:", error);
      }
    },

    // 人工入库模式下通过物料编码查询物料（使用MaterialApi.getMaterialPage）
    async searchMaterialByCode() {
      if (!this.searchForm.materialCode) {
        uni.showToast({
          title: "请输入物料编码",
          icon: "none",
          duration: 2000,
        });
        return;
      }
      console.log("searchMaterialByCode当前出库类型:", this.currentOutType);
      try {
        this.isLoading = true;

        // 使用MaterialApi.getMaterialPage查询物料
        const params = {
          materialCode: this.searchForm.materialCode,
        };

        const response = await MaterialApi.getMaterialByCode(params);

        if (response.code === 0 && response.data) {
          // 清空现有物料表
          this.materialTable = [];

          // 处理返回的物料数据（单个对象）
          const materialData = response.data;
          const materialRow = {
            id: Date.now(), // 为物料生成唯一ID
            materialName: materialData.materialName || "未知物料",
            materialCode:
              materialData.materialCode || this.searchForm.materialCode,
            prodCount: 0, // 净重，初始为0，用户可编辑
            transCount: 0, // 数量，初始为0，用户可编辑
            weight: 0, // 重量字段，用于统一计算
            quantity: 0, // 数量字段，用于统一计算
          };

          this.materialTable = [materialRow];

          uni.showToast({
            title: "已获取物料信息",
            icon: "success",
            duration: 1500,
          });
        } else {
          // 如果查询不到数据，创建基础物料行
          const materialRow = {
            id: Date.now(),
            materialName: "未知物料",
            materialCode: this.searchForm.materialCode,
            prodCount: 0,
            transCount: 0,
            weight: 0,
            quantity: 0,
          };

          this.materialTable = [materialRow];

          uni.showToast({
            title: "未找到物料主数据",
            icon: "none",
            duration: 2000,
          });
        }
      } catch (error) {
        console.error("查询物料失败:", error);
        uni.showToast({
          title: "查询失败，请重试",
          icon: "none",
          duration: 2000,
        });
      } finally {
        this.isLoading = false;
      }
    },

    // 选择单据/合同
    selectDocument(item) {
      // 根据选择的单据加载物料明细
      if (this.currentInType === "purchase") {
        this.loadContractMaterials(item);
      } else {
        this.addMaterialToList(item);
      }
      this.showDocumentList = false;
    },

    // 加载合同物料
    async loadContractMaterials(contract) {
      try {
        // 这里应该调用合同明细接口
        // 临时使用示例数据
        const materials = [
          {
            materialCode: "MAT001",
            materialName: "钢材A",
            quantity: 100,
            unit: "吨",
            weight: 100000,
          },
        ];
        this.materialList = [...this.materialList, ...materials];
      } catch (error) {
        console.error("加载合同物料失败:", error);
      }
    },

    // 添加物料到列表
    addMaterialToList(material) {
      const exists = this.materialList.find(
        (item) => item.materialCode === material.materialCode
      );
      if (!exists) {
        this.materialList.push({
          materialCode: material.materialCode,
          materialName: material.materialName,
          quantity: 0,
          weight: 0,
          unit: material.unit || "件",
        });
      }
    },

    // 从物料表格添加到主物料列表，待保存专用
    addToMaterialList(item) {
      // 检查重量或数量是否有不为0的值
      const weight = Number(item.prod_count) || 0;
      const quantity = Number(item.trans_count) || 0;

      // 如果重量和数量都为0，标记为错误状态并提示
      if (weight === 0 && quantity === 0) {
        this.$set(item, "showError", true);
        uni.showToast({
          title: "重量和数量不能同时为0",
          icon: "none",
          duration: 2000,
        });
        return;
      }

      // 清除错误状态
      this.$set(item, "showError", false);

      // 标记该行为已确认（浅绿色）
      this.$set(item, "isCheck", true);

      // 创建要添加的物料对象
      const material = {
        materialCode: item.materialCode,
        materialName: item.materialName,
        quantity: quantity,
        weight: weight,
        unit: item.unit || "件",
        spec: item.spec || "", // 保留规格信息
        brand: item.brand || "", // 保留品牌信息
        isFromTable: true, // 标记为从表格添加的物料
        originalIndex: this.materialTable.indexOf(item), // 记录原始索引
      };

      // 查找是否已存在相同物料编码的物料
      const existingIndex = this.materialList.findIndex(
        (m) => m.materialCode === material.materialCode
      );

      if (existingIndex !== -1) {
        // 如果已存在，更新现有物料的重量和数量
        this.$set(this.materialList, existingIndex, {
          ...this.materialList[existingIndex],
          weight: weight,
          quantity: quantity,
          spec: item.spec || this.materialList[existingIndex].spec || "",
          brand: item.brand || this.materialList[existingIndex].brand || "",
          isFromTable: true,
          originalIndex: this.materialTable.indexOf(item),
        });
      } else {
        // 如果是新物料，添加到列表中
        // 查找最后一个从表格添加的物料位置
        let insertIndex = this.materialList.length;
        for (let i = this.materialList.length - 1; i >= 0; i--) {
          if (this.materialList[i].isFromTable) {
            insertIndex = i + 1;
            break;
          }
        }

        // 在适当位置插入新物料
        this.materialList.splice(insertIndex, 0, material);
      }

      // 显示成功提示
      uni.showToast({
        title: "物料已添加到待入库列表",
        icon: "success",
        duration: 1500,
      });
    },

    // 添加物料
    addMaterial() {
      if (this.currentInType === "purchase" && this.materialList.length === 0) {
        uni.showModal({
          title: "提示",
          content: "没有入库申请单据，确认人工入库操作？",
          success: (res) => {
            if (res.confirm) {
              this.showMaterialSelector();
            }
          },
        });
      } else {
        this.showMaterialSelector();
      }
    },

    // 显示物料选择器
    showMaterialSelector() {
      // 这里应该弹出物料选择器
      // 临时添加一个示例物料
      this.materialList.push({
        materialCode: "MAT" + Date.now(),
        materialName: "新物料",
        quantity: 0,
        weight: 0,
        unit: "件",
      });
    },

    // 移除物料
    removeMaterial(index) {
      this.materialList.splice(index, 1);
    },

    // 移除选中的待入库物料
    removeSelectedMaterial(item, index) {
      // 显示确认对话框
      uni.showModal({
        title: "确认移除",
        content: `确定要移除物料 "${item.materialName}" 吗？`,
        confirmText: "确定",
        cancelText: "取消",
        success: (res) => {
          if (res.confirm) {
            // 用户确认移除
            this.performRemoveMaterial(item);
          }
        },
      });
    },

    // 执行移除物料操作
    performRemoveMaterial(item) {
      // 找到要移除的物料在materialList中的索引
      const index = this.materialList.findIndex(
        (m) =>
          m.materialCode === item.materialCode &&
          m.materialName === item.materialName
      );

      if (index > -1) {
        // 从materialList中移除物料
        this.materialList.splice(index, 1);

        // 如果该物料是从materialTable添加的，需要清除原表格中的选中状态
        if (item.isFromTable && item.originalIndex !== undefined) {
          const originalItem = this.materialTable[item.originalIndex];
          if (originalItem && originalItem.materialCode === item.materialCode) {
            // 清除原表格项的选中状态
            this.$set(originalItem, "isCheck", false);
            this.$set(originalItem, "showError", false);
            // 清空输入框的值
            this.$set(originalItem, "prod_count", 0);
            this.$set(originalItem, "trans_count", 0);
          }
        }

        uni.showToast({
          title: "已移除待入库物料",
          icon: "success",
          duration: 1500,
        });
      } else {
        uni.showToast({
          title: "移除失败：未找到物料",
          icon: "none",
          duration: 1500,
        });
      }
    },

    // 数字输入校验
    validateNumber(event, item, field) {
      const value = event.detail.value;

      // 处理空值情况
      if (value === "" || value === null || value === undefined) {
        item[field] = "";
        this.updateMaterialStatistics();
        return;
      }

      // 只允许正数和最多2位小数
      const reg = /^\d*\.?\d{0,2}$/;
      if (!reg.test(value)) {
        // 非法输入，恢复原值
        this.$nextTick(() => {
          item[field] = this.formatNumberValue(item[field]);
        });
      }
      // 输入变化时更新统计信息
      this.updateMaterialStatistics();
    },

    // 数字格式化（保留2位小数）
    formatNumber(item, field) {
      const value = Number(item[field]);
      if (!isNaN(value) && value >= 0) {
        item[field] = value.toFixed(2);
      } else {
        item[field] = "0.00";
      }
    },

    // 格式化数字值
    formatNumberValue(value) {
      const num = Number(value);
      if (!isNaN(num) && num >= 0) {
        return num.toFixed(2);
      }
      return "0.00";
    },

    // 设置查询时间范围
    setQueryDateRange(startDate, endDate) {
      this.queryParams.startDate = startDate;
      this.queryParams.endDate = endDate;
      this.formData.inDate = startDate;
    },

    // 获取查询时间范围
    getQueryDateRange() {
      if (this.queryParams.startDate && this.queryParams.endDate) {
        return {
          startDate: this.queryParams.startDate,
          endDate: this.queryParams.endDate,
        };
      }
      // 如果没有设置时间范围，使用当前表单日期
      return {
        startDate: this.formData.inDate,
        endDate: this.formData.inDate,
      };
    },

    // 检斤模式提交验证
    async validateWeighSubmit() {
      console.log(
        "【检斤模式提交验证】",
        this.selectedWeightRows,
        this.selectedContract
      );
      // 检查是否选中了检斤记录
      const hasWeightSelected = this.selectedWeightRows.length > 0;

      // 检查是否选中了合同记录
      const hasContractSelected = this.selectedContract !== null;

      // 如果contractTable没有选中行信息，weightTable没有选中行信息，则进行相应提示
      if (!hasWeightSelected && !hasContractSelected) {
        return {
          valid: false,
          message: "请先选择检斤记录和采购合同",
        };
      }

      // 如果只有检斤记录没有选中合同
      if (hasWeightSelected && !hasContractSelected) {
        return {
          valid: false,
          message: "请先选择采购合同",
        };
      }

      // 如果只有合同没有选中检斤记录
      if (!hasWeightSelected && hasContractSelected) {
        return {
          valid: false,
          message: "请先选择检斤记录",
        };
      }

      // 如果都选中了，判断contractTable的物料名称是否相同
      if (hasWeightSelected && hasContractSelected) {
        // 获取选中合同的物料名称
        const contractMaterialName = this.selectedContract.materialName;

        // 获取选中检斤记录的物料名称列表
        const weightMaterialNames = this.selectedWeightRows
          .map((item) => item.product)
          .filter((name) => name);

        // 检查检斤记录的物料名称是否与合同一致
        const hasDifferentMaterial = weightMaterialNames.some(
          (name) => name !== contractMaterialName
        );

        if (hasDifferentMaterial) {
          // 显示确认对话框
          return new Promise((resolve) => {
            uni.showModal({
              title: "物料名称不一致",
              content: "采购合同和检斤单物料名称不同，确认是否入库？",
              confirmText: "确认入库",
              cancelText: "取消",
              success: (res) => {
                resolve({
                  valid: res.confirm,
                  message: res.confirm ? "" : "已取消入库操作",
                });
              },
            });
          });
        }
      }

      return { valid: true };
    },

    // 表单验证
    validateForm() {
      if (!this.formData.warehouseName) {
        return { valid: false, message: "请选择仓库" };
      }

      if (!this.formData.queryDate) {
        return { valid: false, message: "请选择入库日期" };
      }
      if (this.currentInType === "weigh") {
      } else {
        if (
          !this.selectedMaterialRows ||
          this.selectedMaterialRows.length === 0
        ) {
          return { valid: false, message: "请选择物料明细" };
        }
        // 验证物料明细
        for (let i = 0; i < this.selectedMaterialRows.length; i++) {
          const item = this.selectedMaterialRows[i];

          if (!item.materialName || item.materialName.trim() === "") {
            return { valid: false, message: `第${i + 1}条物料名称不能为空` };
          }

          if (!this.isValidNumber(item.prodCount) || item.prodCount < 0) {
            return { valid: false, message: `第${i + 1}条物料重量必须大于0` };
          }

          if (!this.isValidNumber(item.transCount) || item.transCount < 0) {
            return { valid: false, message: `第${i + 1}条物料数量必须大于0` };
          }

          // 验证数值范围
          if (item.prodCount > 999999) {
            return { valid: false, message: `第${i + 1}条物料重量超出范围` };
          }

          if (item.transCount > 999999) {
            return { valid: false, message: `第${i + 1}条物料数量超出范围` };
          }
        }
      }

      return { valid: true };
    },

    // 验证数字有效性
    isValidNumber(value) {
      return (
        value !== null &&
        value !== undefined &&
        !isNaN(value) &&
        isFinite(value)
      );
    },

    // 构建提交数据（新API格式）
    buildNewSubmitData() {
      // 根据当前入库类型映射到对应的inType值
      const inTypeMap = {
        领料出库: "领料出库",
        人工出库: "人工出库",
        调拨出库: "调拨出库",
      };

      // 构建主表数据
      const mainData = {
        id: null, // 新增时传null
        mainNo: "", // 系统自动生成
        outType: inTypeMap[this.currentInType] || "领料出库",
        warehouseCode:
          this.currentWarehouse?.warehouseCode || this.formData.warehouseId,
        warehouseName:
          this.currentWarehouse?.warehouseName || this.formData.warehouseName,
        ywDate: dateHelperApi.formatDateTime(this.formData.queryDate), // 后端要求格式：yyyy-MM-dd HH:mm:ss
        busMemo: "",
        reserveVarchar1: this.formData.reserveVarchar1, // 领料部门
        reserveVarchar2: this.formData.reserveVarchar2, // 领料工序
        details: [],
      };

      // 根据入库类型添加额外字段

      mainData.details = this.selectedStockRows.map((item, index) => {
        const detail = {
          ywDate: dateHelperApi.formatDateTime(this.formData.queryDate), // 后端要求格式：yyyy-MM-dd HH:mm:ss
          prodCount: Number(item.outProdCount || 0),
          countUnit: "KG",
          transCount: Number(item.outTransCount || 0),
          tranUnit: item.transUnit || "件",
          materialCode: item.materialCode || "",
          materialName: item.materialName.trim(),
          warehouseCode:
            this.currentWarehouse?.warehouseCode || this.formData.warehouseId,
          warehouseName:
            this.currentWarehouse?.warehouseName || this.formData.warehouseName,
          prodPrice: item.prodPrice || 0,
          budgetAmount: item.budgetAmount || 0,
          spec: item.spec || "",
          brand: item.brand || "",
          prodCompany: item.prodCompany || "",
          categoryName: item.categoryName || "",
          picNo: item.picNo || "",
          batchNoSerial: item.batchNoSerial || "",
          steelGradeName: item.steelGradeName || "",
          standardName: item.standardName || "",
          soDiameter: item.soDiameter || "",
          soWidth: item.soWidth || "",
          soThick: item.soThick || "",
          //合同行号
          poContractDetailCode: item.poContractDetailCode || "",
          soLength: item.soLength || "",
        };

        return detail;
      });

      return mainData;
    },

    // 显示提交确认
    showSubmitConfirm(submitData) {
      return new Promise((resolve) => {
        const materialCount = submitData.details
          ? submitData.details.length
          : 0;
        const totalWeight = submitData.details
          ? submitData.details.reduce(
              (sum, item) => sum + (Number(item.prodCount) || 0),
              0
            )
          : 0;
        const totalQuantity = submitData.details
          ? submitData.details.reduce(
              (sum, item) => sum + (Number(item.transCount) || 0),
              0
            )
          : 0;

        uni.showModal({
          title: "确认提交",
          content: `共${materialCount}条物料，总重量：${totalWeight}KG，总数量：${totalQuantity}，是否确认提交？`,
          confirmText: "确认",
          cancelText: "取消",
          success: (res) => {
            resolve(res.confirm);
          },
        });
      });
    },

    // 处理提交成功
    async handleSubmitSuccess(res) {
      uni.showToast({
        title: "出库单创建成功",
        icon: "success",
        duration: 2000,
      });

      // 记录成功日志
      console.log("出库单创建成功:", res.data);

      // 重置表单
      this.resetForm();
    },

    // 处理提交异常
    async handleSubmitException(error) {
      console.error("提交表单异常:", error);

      let errorMsg = "提交失败，请重试";

      // 网络错误处理
      if (error.message && error.message.includes("Network")) {
        errorMsg = "网络连接失败，请检查网络后重试";
      } else if (error.code === "ECONNABORTED") {
        errorMsg = "请求超时，请稍后重试";
      } else if (error.response && error.response.status) {
        switch (error.response.status) {
          case 400:
            errorMsg = "请求参数错误，请检查输入数据";
            break;
          case 401:
            errorMsg = "登录已过期，请重新登录";
            break;
          case 403:
            errorMsg = "没有权限执行此操作";
            break;
          case 500:
            errorMsg = "服务器错误，请稍后重试";
            break;
          default:
            errorMsg = `服务器错误 (${error.response.status})，请稍后重试`;
        }
      }

      uni.showModal({
        title: "提交失败",
        content: errorMsg,
        showCancel: false,
        confirmText: "知道了",
      });
    },
  },
};
</script>

<style scoped lang="scss">
@import "~@/pages/smart/scss/create.scss";

/* 查询TAB样式 */
.query-tabs-section {
  margin-top: 20rpx;
  background-color: #ffffff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.query-tabs {
  display: flex;
  background-color: #f5f5f5;
  border-bottom: 2rpx solid #e0e0e0;
}

.query-tab-item {
  flex: 1;
  padding: 24rpx 0;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;

  &.active {
    background-color: #ffffff;
    color: #1890ff;
    font-weight: 500;

    &::after {
      content: "";
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 4rpx;
      background-color: #1890ff;
    }
  }

  &:not(.active):hover {
    background-color: #f0f0f0;
  }
}

.query-tab-text {
  font-size: 28rpx;
  line-height: 1.5;
}

.query-tab-content {
  padding: 20rpx;

  .section-header {
    margin-bottom: 20rpx;
    padding-bottom: 16rpx;
    border-bottom: 2rpx solid #f0f0f0;
  }

  .section-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333333;
    margin-bottom: 8rpx;
    display: block;
  }

  .section-subtitle {
    font-size: 24rpx;
    color: #999999;
    display: block;
    margin-bottom: 16rpx;
  }

  .empty-stock-tip {
    padding: 40rpx 20rpx;
    text-align: center;
    background-color: #fafafa;
    border-radius: 8rpx;
    margin: 20rpx 0;
  }

  .empty-tip-text {
    font-size: 28rpx;
    color: #999999;
  }

  .form-item {
    display: flex;
    align-items: center;
    gap: 16rpx;
    margin-top: 16rpx;
  }

  .form-input {
    flex: 1;
    height: 72rpx;
    padding: 0 20rpx;
    border: 2rpx solid #d9d9d9;
    border-radius: 8rpx;
    font-size: 28rpx;
    transition: border-color 0.3s ease;

    &:focus {
      border-color: #1890ff;
      outline: none;
    }
  }
}
</style>
